package com.xhwl.centiotdata.suppliersystem.keytopLocal;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.xhwl.centiotdata.pojo.constant.KeyTopLocalConstant;
import com.xhwl.centiotdata.pojo.dto.keytoplocal.VisitorInfoKeyTopLocalDTO;
import com.xhwl.centiotdata.pojo.dto.visitor.VisitorIntegrationConfigDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.common.dto.cent.visitor.VisitorAuthDTO;
import com.xhwl.common.dto.cent.visitor.VisitorInfoDTO;
import com.xhwl.common.dto.cent.visitor.VisitorOpenDTO;
import com.xhwl.common.enums.CodeEnum;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.utils.ChkUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author msy
 */
@Slf4j
@Service
public class VisitorKeyTopLocalHandler {

    @Autowired
    private GeneralKeyTopLocalHandler generalKeyTopLocalHandler;

    @Autowired
    IDeviceCentService deviceCentService;

    public VisitorOpenDTO createVisitorAuth(VisitorIntegrationConfigDTO config, VisitorInfoKeyTopLocalDTO visitorInfoKeyTopLocalDTO, VisitorAuthDTO authDTO) {
        log.warn("访客预约集成配置为：{}",config);
        Map<String, Object> params = BeanUtil.beanToMap(visitorInfoKeyTopLocalDTO);
        JSONObject result = generalKeyTopLocalHandler.post(KeyTopLocalConstant.OWNER_INVITE, params, config.getProjectId(), config.getProductId(),
                config.getIpAndPort(), config.getLoginName(), config.getPassword());
        JSONArray data = result.getJSONArray("data");
        if(ChkUtil.isNull(data)) {
            log.error("访客邀请失败： {}", result);
            throw new BusinessException("访客邀请失败");
        }
        // 科拓访客申请时，每个访客都对应一个id，所以此处把所有返回的id用逗号组合起来当场第三方id
        String openId = data.toList(String.class).stream().collect(Collectors.joining(","));
        VisitorOpenDTO visitorOpenDTO = new VisitorOpenDTO();
        visitorOpenDTO.setId(authDTO.getId());
        visitorOpenDTO.setOpenId(openId);
        return visitorOpenDTO;
    }

    public JSONArray queryArea(VisitorIntegrationConfigDTO config, String openId) {
        Map<String, Object> params = new HashMap<>();
        params.put("ownerId", openId);

        JSONObject result = generalKeyTopLocalHandler.post(KeyTopLocalConstant.GET_VISITOR_AREA, params,
                config.getProjectId(), config.getProductId(),
                config.getIpAndPort(), config.getLoginName(), config.getPassword());
        JSONArray data = result.getJSONArray("data");
        if(ChkUtil.isNull(data)) {
            log.error("该业主没有授权区域: params: {},  result: {}", params, result);
            throw new BusinessException();
        }
        return data;
    }

    public ResultJson deleteVisitorAuth(VisitorIntegrationConfigDTO config, VisitorInfoDTO infoDTO, String openId) {
        if(ChkUtil.isNotNull(infoDTO.getOpenId())) {
            // 访客申请时，第三方id是科拓返回的每个访客id组合起来的，此处要分割
            List<String> openIds = Arrays.asList(infoDTO.getOpenId().split(","));
            for(String id : openIds) {
                Map<String, Object> params = new HashMap<>();
                params.put("id", id);
                params.put("ownerId", openId);

                generalKeyTopLocalHandler.post(KeyTopLocalConstant.OWNER_CANCEL_INVITE, params, config.getProjectId(), config.getProductId(),
                        config.getIpAndPort(), config.getLoginName(), config.getPassword());
            }

            return ResultJson.success();
        }
        return ResultJson.fail("没有关联的第三方访客申请记录id");
    }

    public ResultJson getQrCode(VisitorIntegrationConfigDTO config, VisitorAuthDTO visitorAuthDTO) {
        Map<String, Object> params = new HashMap<>();
        params.put("id", visitorAuthDTO.getOpenId());

        JSONObject result = generalKeyTopLocalHandler.post(KeyTopLocalConstant.GET_QRCODE, params, config.getProjectId(), config.getProductId(),
                config.getIpAndPort(), config.getLoginName(), config.getPassword());
        JSONObject data = result.getJSONObject("data");
        if(ChkUtil.isNotNull(data)) {
            String qrCode = data.getStr("qrCode");
            return ResultJson.success(CodeEnum.SUCCESS.description, qrCode);
        }
        log.error("获取访客二维码失败: {}", result);
        return ResultJson.fail("获取访客二维码失败");
    }
}
